<?php
namespace app\admin\controller;

/**
 * 管理员控制器
 */
class AuthMember extends Base
{

    /**
     * 系统管理员
     * @return html
     */
    public function index() {
        $username = trim( input( 'username' ) );
        $nickname = trim( input( 'nickname' ) );
        $where    = [];
        $where['is_remove'] = 1;
        $where['user_type'] = 1;//系统管理员
        $username && $where['username'] = ['like', '%'.$username.'%'];
        $nickname && $where['nickname'] = ['like', '%'.$nickname.'%'];

        $order = 'uid ASC';
        $field = 'uid, username, nickname, ctime, status';
        //分页查询列表
        $list  = db( 'auth_member' )->where( $where )->field( $field )->order( $order )
                ->paginate( 20, false, ['query'=>request()->param()] );
        //获取分页数据
        $data  = $list->items();


        
        $this->assign( 'list', $list );
        $this->assign( 'data', $data );
        return $this->fetch();
    }
    
    /**
     * 添加系统管理员
     * @return html
     */
    public function add()
    {
        if( request()->isPost() ) {
            $data        = input();

            //检测用户名是否存在
            $username = isset( $data['username'] ) && trim( $data['username'] ) ?
                        trim( $data['username'] ) : '';
            if( !$username ) {
                $this->error( '登录名不能为空' );exit;
            }

            //判断是否选择角色
            if( !isset( $data['role_id'] ) || !$data['role_id'] ) {
                $this->error( '请选择角色' );exit;
            }
            $roleId = $data['role_id'];
            unset( $data['role_id'] );



            //判断是否存在回收站
            $userExists = db( 'auth_member' )->field( 'uid, is_remove' )
                          ->where( ['username'=>$username] )->find();
            if( $userExists && $userExists['is_remove'] == 2 ) {
                $this->error( '该管理员已经存在回收站，请到回收站恢复' );exit;
            }

            $auth_member = model( 'AuthMember' );
			//dump($data);
            //$valid       = \think\Loader::validate( "AuthMember" )->scene( 'add' );
			$valid 		 = new \app\admin\validate\AuthMember;
			//$valid 		 = new \app\admin\validate\Menu;
			
            if( !$valid->check( $data ) ) {
				
                $this->error( $valid->getError() );
            } else {
				
                $uid = $auth_member->addMember( $data );
                if( $uid > 0 ) {
                    //添加角色
                    if ( $roleId ) {
                        //添加权限
                        $insertData            = [];
                        $insertData['uid']     = $uid;
                        $insertData['role_id'] = $roleId;
						
                        db( 'auth_role_member' )->insertGetId( $insertData );
                    }

                    //操作日志
                    add_system_log( $this->uid, 1, 1, '添加系统管理员' );
                    $this->success( '添加成功', url( 'auth_member/index' ) );
                } else {
                    $this->error( '添加失败' );
                }
            }
        } else {
            //角色
            $where           = [];
            $where['status'] = 1;
            $authGroup = db( 'auth_role' )->field( 'id, title' )->where( $where )->select();
            $this->assign( 'authGroup', $authGroup );
            //部门
            /*$where           = [];
            $where['status'] = 1;
            $postList        = db( 'auth_post' )->where( $where )->select();
            $this->assign( 'postList', $postList );*/
            return $this->fetch();
        }
    }
    
    /**
     * 编辑
     * @return html
     */
    public function edit()
    {
        $uid  = intval( input( 'uid' ) );
        
        if( !$uid ) {
            $this->error( '非法操作' );
        }
        if( request()->isPost() ) {
            $data = input();
            //判断是否选择角色
            if( $data['uid'] != 1 ) {
                if( !isset( $data['role_id'] ) || !$data['role_id'] ) {
                    $this->error( '请选择角色' );exit;
                }
                $roleId = $data['role_id'];
                unset( $data['role_id'] );


            }

            $auth_member = model('AuthMember');
            if( $data['password'] ) {
				$valid 		 = new \app\admin\validate\AuthMember;
                //$valid   = \think\Loader::validate( "AuthMember" )->scene( 'edit_pwd' );
            } else {
				$valid 		 = new \app\admin\validate\AuthMember;
                //$valid   = \think\Loader::validate( "AuthMember" )->scene( 'edit' );
            }
            if( !$valid->check( $data ) ) {
                $this->error( $valid->getError() );
            } else {
                if( $auth_member->editMember( $data, ['uid'=>$data['uid']] ) ) {

                    //管理员角色处理
                    if( $data['uid'] != 1 ) {
                        //当前用户权限关联
                        $updateData            = [];
                        $updateData['role_id'] = $roleId;
			
                        db( 'auth_role_member' )->where( ['uid'=>$uid] )->update( $updateData );
                    }

                    //操作日志
                    add_system_log( $this->uid, 1, 2, '编辑系统管理员' );
                    $this->success( '编辑成功', url( 'auth_member/index' ) );
                } else {
                    $this->error( '编辑失败' );
                }
            }
        } else {
            $find = model( 'AuthMember' )->getFindOne( $uid );
            $this->assign( 'find', $find );

            //角色
            $where           = [];
            $where['status'] = 1;
            $authGroup  = db( 'auth_role' )->field( 'id, title' )->where( $where )->select();
            $this->assign( 'authGroup', $authGroup );
            $selectRole = db( 'auth_role_member' )->where( ['uid'=>$uid] )->value( 'role_id' );
            $this->assign( 'selectRole', $selectRole );

            
            return $this->fetch();
        }
    }
    
    /**
     * 状态
     * @return html
     */
    public function state() {
        $uid    = input( 'uid' );
        $status = input( 'status' );
        if( $uid && $status ) {
            $uidArr = explode( ',', $uid );
            if( in_array( '1', $uidArr ) ) {
                $this->error( 'admin超级管理员不能禁用' );
            }
            $map = [
                'uid' => ['in',$uidArr],
            ];
            if( model( 'AuthMember' )->stateMember( $map, ['status'=>$status] ) ) {
                //操作日志
                $acname = $status == 1 ? '启用' : '禁用';
                add_system_log( $this->uid, 1, 2, $acname.'系统管理员' );
                $this->success( '设置成功' );
            } else {
                $this->error( '设置失败' );
            }
        } else {
            $this->error( '参数有误' );
        }
    }
    
    /**
     * 删除
     * @return html
     */
    public function remove() {
        $data = input( 'uid' );
        if( $data ) {
            $auth_member = model( 'AuthMember' );
            if( $auth_member->removeMember( $data ) ) {
                //操作日志
                add_system_log( $this->uid, 1, 4, '删除系统管理员' );
                $this->success( '删除成功' );
            } else {
                $this->error( '删除失败' );
            }
        } else {
            $this->error( '提交的数据有误' );
        }
    }
    
    /**
     * 授权
     * @return html
     */
    public function tgauthor() {
        $this->error( '非法操作' );exit;
        if( request()->isPost() ) {
            $data = input();

            //角色必填
            if( !isset( $data['id'] ) || !$data['id'] ) {
                $this->error( '请选择授权角色' );
            }

            //当前用户权限关联
            $groupAccess = db( 'auth_role_member' )->where( ['uid'=>$data['uid']] )->select();

            //用户权限组
            $groupIdArr = array_column( $groupAccess, 'role_id' );

            //权限组与授权权限差集
            //删除的权限
            $delGroupAccess = array_diff( $groupIdArr, $data['id'] );
            //添加的权限
            $insertGroupAccess = array_diff( $data['id'], $groupIdArr );
            
            if ( $delGroupAccess ) {
                //删除权限
                $map            = [];
                $map['uid']     = $data['uid'];
                $map['role_id'] = [ 'in', $delGroupAccess ];
                db( 'auth_role_member' )->where( $map )->delete();    
            }

            if ( $insertGroupAccess ) {
                //添加权限
                $insertGroup = [];
                foreach ($insertGroupAccess as $key => $role_id) {
                    $insertGroup[$key]['uid']     = $data['uid'];
                    $insertGroup[$key]['role_id'] = $role_id;
                }
                db( 'auth_role_member' )->insertAll( $insertGroup );
            }
            
            if ( $delGroupAccess && !$insertGroupAccess ) {
                $this->success( '撤销成功', url( 'auth_member/index' ) );    
            } else {
                $this->success( '授权成功', url( 'auth_member/index' ) );    
            }
        } else {
            $uid  = input( 'uid' );
            $where           = [];
            $where['status'] = 1;
            $list = db( 'auth_role' )->where( $where )->select();
            $mgs  = db( 'auth_role_member' )->where( ['uid'=>$uid] )->select();
            $checked = [];
            if( $mgs ) {
                foreach( $mgs as $value) {
                    $checked[] = $value['role_id'];
                }
            }
            $this->assign( 'mgs', $checked );
            $this->assign( 'list', $list );
            $this->assign( 'uid', $uid );
            return $this->fetch();
        }
    }

    /**
     * 角色岗位
     * @return html
     */
    public function rolePost() {
        $roleId = intval( input( 'role_id' ) );
        if( !$roleId ) {
            $this->error( '请选择角色' );
        }
        //获取数据权限
        $dataAuth = db( 'auth_role' )->where( ['id'=>$roleId] )->value( 'data_auth' );

        //获取该数据权限下的岗位
        $where              = [];
        $where['data_auth'] = $dataAuth;
        $order    = 'sort ASC, id DESC';
        $field    = 'id, name';
        $authPost = db( 'auth_post' )->field( $field )->where( $where )->order( $order )->select();
        $this->success( 'ok', '', $authPost );
    }
    
}